import React from 'react';
import { inject, observer } from 'mobx-react';
import { Spin, Button, Icon, Modal, Table,message } from 'antd'
import { WeaPopoverHrm, WeaNewScroll, WeaSearchGroup, WeaFormItem, WeaInput, WeaRichText, WeaTableEditable, WeaLocaleProvider } from 'ecCom';
import * as Util from '../../util/Util'
const getLabel = WeaLocaleProvider.getLabel;
const toJS = mobx.toJS;

@inject('knowledgeEditStore')
@observer
export default class KnowledgeEdit extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            columns: [
                {
                    title: <span>{getLabel(229, "标题")}</span>,
                    dataIndex: 'title',
                    key: 'title',
                    width: '*',
                    com: [
                        { type: 'INPUT', viewAttr: 3, key: 'title', placeholder: getLabel(229, "标题"), viewAttr: 2, defaultValue: '' },
                    ],
                },
                {
                    title: <span>{getLabel(17908, "指定知识文档")}</span>,
                    dataIndex: 'docIds',
                    key: 'docIds',
                    width: '20%',
                    com: [
                        { type: 'BROWSER', key: 'docIds', browserConditionParam: { type: 9, isSingle: false }, viewAttr: 2, defaultValue: '' },
                    ],
                },
                {
                    title: <span>{getLabel(23209, "动态参考文档")}</span>,
                    dataIndex: 'sqlstr',
                    key: 'sqlstr',
                    width: '20%',
                    com: [
                        { type: 'TEXTAREA', key: 'sqlstr', placeholder: getLabel(23209, "动态参考文档"), viewAttr: 2, defaultValue: '' },
                    ],
                },
                {
                    title: <span>{getLabel(6071, "权重")}(%)</span>,
                    dataIndex: 'rate',
                    key: 'rate',
                    width: '20%',
                    com: [
                        { type: 'INPUTNUMBER', key: 'rate', defaultValue: 0, viewAttr: 2 },
                    ],
                },
                {
                    title: <span>{getLabel(338, "排序")}</span>,
                    dataIndex: 'sort',
                    key: 'sort',
                    width: '20%',
                    com: [
                        { type: 'INPUTNUMBER', key: 'sort', defaultValue: 0, viewAttr: 2 },
                    ],
                },
            ],
            refeshid: -1,
            viewHeight: this.getHeight(),
            knowledgeId: "",// || this.props.knowledgeId
            operation: "",// || this.props.operation
            selectedRowKeys:[]
        }
        this.isfresh = true;
    }
    componentWillMount() {//一些初始化请求
        this.initKnowledgePage(this.props);
    }
    componentWillUnmount() {
        this.cleanValues();
    }
    componentWillReceiveProps(newProps) {
        if (newProps.operation == 'add') {
            this.cleanValues();
        }
        this.initKnowledgePage(newProps);
    }

    cleanValues() {
        let { knowledgeEditStore } = this.props;
        knowledgeEditStore.name = "";
        knowledgeEditStore.remark = "";
        knowledgeEditStore.datas = [];
    }


    initKnowledgePage(props) {
        const { knowledgeEditStore } = this.props;
        let { columns } = this.state;
        let operation = Util.getParams("operation") || props.operation;
        let knowledgeId = Util.getParams("knowledgeId") || props.knowledgeId;
        this.setState({ knowledgeId: knowledgeId, operation: operation });
        if (operation == "edit" || operation == "add") {
            columns.map((element, index) => {
                element.com[0].viewAttr = 2;
            })
        } else if (operation == "view") {
            columns.map((element, index) => {
                element.com[0].viewAttr = 1;
            })
        }
        if (knowledgeId) {
            knowledgeEditStore.getKnowledgeDetail({ "knowledgeId": knowledgeId });
        }
    }

    editData() {
        let { columns } = this.state;
        this.setState({ operation: 'edit' });
        columns.map((element, index) => {
            element.com[0].viewAttr = 2;
        })
    }

    saveData() {
        const { knowledgeEditStore } = this.props;
        let { name, remark, datas } = knowledgeEditStore;
        let { operation, knowledgeId } = this.state;
        const result = this.refs.tableEdit.doValidate();
        let passStatues = result.pass;
        if (!passStatues) {
            return;
        }
        let sumRate = 0;
        for (let i = 0; i < datas.length; i++) {
            sumRate = sumRate + parseFloat(datas[i].rate);
        }
        if (name.length == 0) {
            Modal.error({
                title: '提示',
                content: '知识点名称不能为空!',
            });
            return;
        }
        if (datas.length>0 && sumRate != 100) {
            Modal.error({
                title: '提示',
                content: '明细权重填写不正确!',
            });
            return;
        }
        let _this = this;
        knowledgeEditStore.saveKnowledge({
            name: name, remark: remark, datas: JSON.stringify(datas), operation: operation, knowledgeId: knowledgeId, doback: function (knowledgeId) {
                message.success('保存成功!', 2);
                let optparams = [];
                optparams.rowid = knowledgeId;
                optparams.opttype = operation;
                optparams.type = ["name"];
                optparams.value = [knowledgeEditStore.name];
                if (typeof _this.props.onCallBackSuccess === "function") {
                    _this.props.onCallBackSuccess(optparams);
                }
            }
        });
    }

    getHeight() {
        let { minusHeight } = this.props;
        if (minusHeight == undefined) {
            minusHeight = 0;
        }
        return window.innerHeight - 110 - minusHeight;
    }

    onInputChange = (values, type, typenName) => {
        let { knowledgeEditStore } = this.props;
        if (knowledgeEditStore[type] != values) {
            knowledgeEditStore[type] = values;
        }
    }

    //添加一行表格数据
    willAdd(datas, addData) {
        const { knowledgeEditStore } = this.props;
        knowledgeEditStore.datas = datas;
    }
    //删除表格数据
    doDelete=(datas, keys)=> {
        const { knowledgeEditStore } = this.props;
        return new Promise((resolve, reject) => {
            Modal.confirm({
                content: `确定要删除吗？ `,
                onOk: () => {
                    resolve(true);
                    let list = [...knowledgeEditStore.datas];
                    for (let j = 0; j < list.length; j++) {
                        for (let i = 0; i < keys.length; i++) {
                            if (list[j].id == keys[i]) {
                                knowledgeEditStore.datas.remove(list[j]);
                            }
                        }
                    }
                },
                onCancel: () => {
                    resolve(false);
                },
            })
        })
    }
    onRowSelect = selectedRowKeys => {
        this.setState({ selectedRowKeys });
      };
    //复制单元格
    willCopy(datas, selectedKeys, copyDatas) {
        const { knowledgeEditStore } = this.props;
        knowledgeEditStore.datas = datas;
    }
    //编辑单元格回调
    willEdit(datas, result) {
        let tip = "";
        let days = 0;
        let flag = false;
        const { key, record, value, index } = result;
        if (flag) {
            if (tip.length > 0) {
                Modal.warning({
                    title: "提示",
                    content: tip,
                });
            }
            datas[index] = record;
            const { knowledgeEditStore } = this.props;
            knowledgeEditStore.datas = datas;
        } else {
            const { knowledgeEditStore } = this.props;
            knowledgeEditStore.datas = datas;
        }

    }

    renderDetail() {
        if (this.isfresh) {
            this.isfresh = false;
            const { knowledgeEditStore } = this.props;
            this.setState({ knowledgeId: this.props.knowledgeId, refeshid: this.props.refeshid });
            knowledgeEditStore.getKnowledgeDetail({ "knowledgeId": this.props.knowledgeId });
        }
    }

    render() {
        let { knowledgeEditStore, _minusHeight } = this.props;
        if (_minusHeight == undefined) { _minusHeight = 0; }
        const { viewHeight, columns, operation, knowledgeId, refeshid } = this.state;
        const { loading, name, remark, datas, hasRight } = knowledgeEditStore;
        if ((knowledgeId != this.props.knowledgeId || refeshid != this.props.refeshid) && (operation == 'edit' || operation == 'view')) {
            this.isfresh = true;
            this.renderDetail();
        }
        return (
            <div className="knowledge-knowledge-edit">
                <div className="knowledge-edit-title-div">
                    <div className="title-Incon"><span className="icon-coms-doc" style={{ fontSize: '16px', float: 'left' }} ></span><b className="title-Incon-name">知识点信息</b></div>
                    {((operation == 'edit' && hasRight == true ) || operation == 'add')  && <div className="title-save" onClick={() => this.saveData()}><Icon type="save" /><b className="title-save-name">保存</b></div>}
                    {operation == 'view' && hasRight == true && <div className="title-save" onClick={() => this.editData()}><Icon type="edit" /><b className="title-save-name">编辑</b></div>}
                </div>
                <WeaNewScroll height={viewHeight - _minusHeight} >
                    <WeaPopoverHrm />
                    <Spin spinning={loading}>
                        < WeaSearchGroup title={getLabel(1361, "基本信息")} needTigger={false} showGroup={true}>
                            <WeaFormItem labelCol={{ span: 4 }} wrapperCol={{ span: 17 }} className="iteamClass" label={getLabel(27915, '知识点名称')} >
                                <WeaInput value={name} viewAttr={operation == "view" ? "1" : "3"} onChange={(val) => this.onInputChange(val, 'name', getLabel(27915, '知识点名称'))} />
                            </WeaFormItem>
                            <WeaFormItem labelCol={{ span: 4 }} wrapperCol={{ span: 17 }} className="iteamClass" label={getLabel(27915, '知识点描述')}  >
                                <WeaRichText
                                    viewAttr={operation == "view" ? 1 : 2}
                                    value={remark}
                                    style={{ marginTop: '20px', marginLeft: '20px', marginRight: '20px', width: '96%' }}
                                    ckConfig={{
                                        toolbar: [
                                            { name: 'document', items: ['Source'] },
                                            { name: 'paragraph', items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight', '-', 'NumberedList', 'BulletedList'] },
                                            { name: 'styles', items: ['Format', 'Font', 'FontSize'] },
                                            { name: 'colors', items: ['TextColor'] },
                                            { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike',] },
                                            { name: 'insert', items: ['Table','Image', 'Smiley'] },
                                        ],
                                        uploadUrl: "/api/knowledge/knowledgeMap/uploadDoc?category=6604", // 上传地址
                                        height: 150,
                                        autoGrow_minHeight: 150,
                                        autoGrow_maxHeight: 150,
                                    }}
                                    onChange={(text) => { this.onInputChange(text, "remark", getLabel(27915, '知识点描述')) }}
                                />
                            </WeaFormItem>
                        </WeaSearchGroup >
                        <WeaSearchGroup title={getLabel(27915, "知识点明细")} needTigger={false} showGroup={true}>
                            <WeaTableEditable
                                viewAttr={operation == "view" ? 1 : 2}
                                ref='tableEdit'
                                columns={columns}
                                datas={toJS(datas)}
                                selectedRowKeys={this.state.selectedRowKeys}
                                willAdd={(datas, addData) => this.willAdd(datas, addData)}
                                willDelete={(datas, keys) => this.doDelete(datas, keys)}
                                onRowSelect={this.onRowSelect}
                                willEdit={(datas, result) => this.willEdit(datas, result)}
                                willCopy={(datas, selectedKeys, copyDatas) => this.willCopy(datas, selectedKeys, copyDatas)}
                                validator={{
                                    rules: {
                                        title: 'required',
                                    },
                                    errorMessage: {
                                        required: '此项必填',
                                    },
                                }
                                }
                            />
                        </WeaSearchGroup>
                    </Spin>
                </WeaNewScroll>
            </div >
        )
    }
};